<template>
  <div class="profile-container">
    <el-card class="profile-card" shadow="always">
      <template #header>
        <div class="header">
          <h2>个人主页</h2>
          <el-button type="primary" plain size="small" @click="reload">刷新</el-button>
        </div>
      </template>

      <el-skeleton v-if="loading" :rows="5" animated />
      <div v-else>
        <!-- 头像区域 -->
        <div class="avatar-section">
          <div class="avatar-container">
            <el-avatar 
              :size="120" 
              :src="user.avatar || info?.avatarUrl" 
              :icon="UserFilled"
              class="avatar"
            />
            <div class="avatar-actions">
              <el-button 
                type="primary" 
                size="small" 
                @click="triggerFileInput"
                :loading="uploading"
              >
                {{ uploading ? '上传中...' : '更换头像' }}
              </el-button>
              <input 
                ref="fileInput" 
                type="file" 
                accept="image/*" 
                style="display: none" 
                @change="handleFileSelect"
              />
            </div>
          </div>
        </div>

        <el-descriptions title="基本信息" :column="1" border>
          <el-descriptions-item label="用户ID">{{ info?.id }}</el-descriptions-item>
          <el-descriptions-item label="用户名">{{ info?.username }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{ info?.email || '-' }}</el-descriptions-item>
          <el-descriptions-item label="手机号">{{ info?.phone || '-' }}</el-descriptions-item>
          <el-descriptions-item label="地址">{{ info?.address || '-' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatTime(info?.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatTime(info?.updateTime) }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { UserFilled } from '@element-plus/icons-vue'
import { useUserStore } from '../stores/user'

const user = useUserStore()
const loading = ref(false)
const uploading = ref(false)
const fileInput = ref<HTMLInputElement>()
const info = computed(() => user.userInfo)

const parseDate = (v: number[] | string | undefined | null) => {
  if (!v) return '-'
  if (Array.isArray(v)) {
    // [YYYY, M, D, h, m, s]
    const [Y, M, D, h = 0, m = 0, s = 0] = v
    const mm = String(M).padStart(2, '0')
    const dd = String(D).padStart(2, '0')
    const hh = String(h).padStart(2, '0')
    const mi = String(m).padStart(2, '0')
    const ss = String(s).padStart(2, '0')
    return `${Y}-${mm}-${dd} ${hh}:${mi}:${ss}`
  }
  return new Date(v).toLocaleString()
}

const formatTime = (v: any) => parseDate(v)

const load = async () => {
  loading.value = true
  try {
    await user.fetchUserInfo()
  } finally {
    loading.value = false
  }
}

const reload = () => load()

const triggerFileInput = () => {
  fileInput.value?.click()
}

const handleFileSelect = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  
  if (!file) return
  
  // 文件类型检查
  if (!file.type.startsWith('image/')) {
    ElMessage.error('请选择图片文件')
    return
  }
  
  // 文件大小检查 (5MB)
  if (file.size > 5 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过5MB')
    return
  }
  
  uploading.value = true
  
  try {
    const avatarUrl = await user.uploadAvatar(file)
    ElMessage.success('头像上传成功')
    console.log('新头像URL:', avatarUrl)
  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error('头像上传失败，请重试')
  } finally {
    uploading.value = false
    // 清空文件输入，允许重复选择同一文件
    if (target) target.value = ''
  }
}

onMounted(() => {
  if (!user.userInfo) load()
})
</script>

<style scoped>
.profile-container {
  padding: 16px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.profile-card {
  max-width: 800px;
  margin: 0 auto;
}

.avatar-section {
  margin-bottom: 24px;
  padding: 20px;
  text-align: center;
  background: #fafafa;
  border-radius: 8px;
}

.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.avatar {
  border: 3px solid #e4e7ed;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.avatar-actions {
  display: flex;
  gap: 8px;
}
</style>